from django.shortcuts import render,redirect
from django.http import HttpResponse
from mydemo.models import User as mydemo_user


# Create your views here.
def test(request):
    return redirect('/mydemo')


def index(request):
    if(request.method=="GET"):
        print("get index page")
        data=mydemo_user.objects.all()

        return render(request, 'mydemo/index.html', {"data":data})

def add(request):
    if request.method=="GET":
        print("get add page!!")

        return render(request,'mydemo/add.html',{})
    if request.method=="POST":
        name = request.POST.get('name')
        age = request.POST.get('age')
        gender = request.POST.get('gender')
        hobby = request.POST.get('hobby')
        email=request.POST.get('email')

        print(name,age,gender,hobby,email)

        user=mydemo_user.objects.create(name=name,age=age,gender=gender,hobby=hobby,email=email)
        user.save()
        return redirect('/mydemo/index')

def delete(request):
    id=int(request.GET.get("id"))
    if id:
        print("id =%d"%id)
        mydemo_user.objects.filter(id = id).delete()

    return redirect("/mydemo")

def edit(request):
    if request.method=="GET":
        id=int(request.GET.get("id"))
        if id:
            print("id=%d"%id)
            user=mydemo_user.objects.filter(id=id).get()
            print(user)

            return render(request,'mydemo/edit.html',{"user":user})

    if request.method == "POST":
        id = int(request.POST.get("id"))
        if id:
            print("id=%d"%id)
            name=request.POST.get("name")
            age = request.POST.get("age")
            gender = request.POST.get("gender")
            hobby = request.POST.get("hobby")
            email = request.POST.get("email")

            print(name,age,gender,hobby,email)

            mydemo_user.objects.filter(id=id).update(
                name=name,
                age=age,
                gender=gender,
                hobby=hobby,
                email=email
            )
            print("updata ok")
            return redirect("/mydemo")

